//
//  SendDataManager.m
//  NuwaRobot
//
//  Created by Kendama on 2018/1/11.
//  Copyright © 2018年 Kendama. All rights reserved.
//

#import "DataManager.h"
#import "DTCMQTTManager.h"
#import <AudioToolbox/AudioToolbox.h>
#import "NewMessageModel.h"
#import "DTCLocalPushManager.h"

@interface DataManager()<EMChatManagerDelegate,DTCMQTTManagerDelegate>


@end

@implementation DataManager
+ (DataManager *)sharedInstance
{
    static DataManager *static_manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        static_manager = [[DataManager alloc]init];
    });
    return static_manager;
}

- (instancetype)init
{
    if ([super init])
    {
        [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
        [[DTCMQTTManager shareManagerWithDeleagate:self] connectToHost:@"testapi.ourslinks.com" port:1883];

    }
    return self;
}

- (void)subscribeTheme
{
    [[DTCMQTTManager shareManagerWithDeleagate:self] subscribeSubject:[NSString stringWithFormat:@"nuwa/%@",EXRACT_OBJECT(DEVICEMAC)]];
}

#pragma mark - <DTCMQTTManagerDelegate>
- (void)mqttManager:(DTCMQTTManager *)manager connectResult:(NSError *)error
{
    if (!error)
    {
        [manager subscribeSubject:[NSString stringWithFormat:@"nuwa/%@",EXRACT_OBJECT(DEVICEMAC)]];
        [manager subscribeSubject:[NSString stringWithFormat:@"nuwa/app/%@",EXRACT_OBJECT(DEVICEMAC)]];
    }
    else
    {
        [manager connectToHost:@"testapi.ourslinks.com" port:1883];
    }
}

- (void)mqttManager:(DTCMQTTManager *)manager messageBack:(NSData *)data topic:(NSString *)topic
{
    NSError *err = nil;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&err];
    NSDictionary *dataDic = dict[@"data"];
    NSString *code = dict[@"code"];
//    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    if ([code isEqualToString:@"1811"]) // 喜马拉雅
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:XiMaLaYa object:nil userInfo:dataDic];
    }
    else if ([code isEqualToString:@"1851"]) // 监控
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:Monitoring object:nil userInfo:dataDic];
    }
    NSLog(@"Topic:%@--MQTT数据：%@",topic,dict);
}

- (void)sendCode:(NSString *)code data:(NSDictionary *)data
{
    NSDictionary *dict = @{@"code":code,@"data":data};
    
    NSData *sendData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    [[DTCMQTTManager shareManagerWithDeleagate:self] publishData:sendData onTopic:[NSString stringWithFormat:@"nuwa/app/%@",EXRACT_OBJECT(DEVICEMAC)]];
}

- (void)sendVideoWithURL:(NSURL *)url
{
    EMMessage *message = [EaseSDKHelper getVideoMessageWithURL:url to:EXRACT_OBJECT(DEVICEMAC) messageType:EMChatTypeChat messageExt:nil];
    [self sendMessage:message];
}

- (void)sendImageWithData:(NSData *)imageData
{
    EMMessage *message = [EaseSDKHelper getImageMessageWithImageData:imageData to:EXRACT_OBJECT(DEVICEMAC) messageType:EMChatTypeChat messageExt:nil];
    [self sendMessage:message];
}

- (void)sendMessage:(EMMessage *)message
{
    [[EMClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
        
    } completion:^(EMMessage *aMessage, EMError *aError) {
        
    }];
}

- (void)messagesDidReceive:(NSArray *)aMessages
{
    EMMessage *message = aMessages.firstObject;
    EMMessageBody *msgBody = message.body;
    EMTextMessageBody *textBody = (EMTextMessageBody *)msgBody;
    NSLog(@"环信收到消息%@",textBody.text);

    [[DTCLocalPushManager defalutService] addLocalNotificationByBody:@"您有一条新消息" date:[NSDate date]];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:HuanXinNewMessage object:nil userInfo:@{@"uid":message.conversationId}];
    NSArray *array = [NewMessageModel selectFromClassPredicateWithFormat:[NSString stringWithFormat:@"where uid = '%@'",message.conversationId]];
    if (array.count == 0)
    {
        NewMessageModel *model = [[NewMessageModel alloc] init];
        model.uid = message.conversationId;
        model.count = @"1";
        [model insertObject];
    }
    else
    {
        NewMessageModel *model = array.firstObject;
        model.count = @"1";
        [model updateObject];
    }
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"message" ofType:@"wav"];
    //定义一个带振动的SystemSoundID
    SystemSoundID soundID = 1007;
    //判断路径是否存在
    if (path) {
        //创建一个音频文件的播放系统声音服务器
        OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)([NSURL fileURLWithPath:path]), &soundID);
        //判断是否有错误
        if (error != kAudioServicesNoError) {
            NSLog(@"%d",(int)error);
        }
    }
    //只播放声音，没振动
    AudioServicesPlaySystemSound(soundID);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
//- (void)cmdMessagesDidReceive:(NSArray *)aCmdMessages
//{
//    for (EMMessage *message in aCmdMessages) {
//        EMCmdMessageBody *body = (EMCmdMessageBody *)message.body;
//        NSLog(@"收到的action是 -- %@",body.action);
//    }
//}


//- (void)sendCode:(NSString *)code data:(NSDictionary *)data
//{
//    NSDictionary *dict = @{@"code":code,@"data":data};
//    EMCmdMessageBody *body = [[EMCmdMessageBody alloc] initWithAction:[self convertToJsonData:dict]];
//    NSString *from = [[EMClient sharedClient] currentUsername];
//    // 生成message
//    EMMessage *message = [[EMMessage alloc] initWithConversationID:@"0123456789abcdef" from:from to:@"0123456789abcdef" body:body ext:nil];
//    message.chatType = EMChatTypeChat;// 设置为单聊消息
//    [[EMClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
//
//    } completion:^(EMMessage *aMessage, EMError *aError) {
//
//    }];
//}

-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

@end
